<template>
  <div class="college-dialog" @click.stop>
    <div class="left">
      <div
        :class="['left-item', currentType === item.value ? 'active' : '']"
        v-for="item in typeList"
        :key="item.value"
        @click="handleChangeType(item)"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="right">
      <div class="main-content" ref="mainContentRef">
        <!-- 院校地区 -->
        <div class="location-list" :ref="(el) => (sectionRefs[0] = el)">
          <div class="type-title">院校地区</div>
          <div
            :class="['location-item']"
            v-for="item in locationProvinceDataList"
            :key="item.code"
          >
            <div class="location-title">{{ item.location }}</div>
            <div class="location-content">
              <div
                :class="['content-item', _item.checked ? 'active' : '']"
                v-for="_item in item.provinceList"
                :key="_item.code"
                @click="handleSelectItem(_item)"
              >
                {{ _item.name }}
              </div>
            </div>
          </div>
        </div>
        <!-- 院校类型 -->
        <div class="type-list" :ref="(el) => (sectionRefs[1] = el)">
          <div class="type-title">院校类型</div>
          <div class="type-content">
            <div
              :class="['content-item', item.checked ? 'active' : '']"
              v-for="item in schoolTypeDataList"
              :key="item.code"
              @click="handleSelectSpe(item, schoolTypeDataList)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <!-- 院校特色 -->
        <div class="type-list" :ref="(el) => (sectionRefs[2] = el)">
          <div class="type-title">院校特色</div>
          <div class="type-content">
            <div
              :class="['content-item feature', item.checked ? 'active' : '']"
              v-for="item in schoolFeatureDataList"
              :key="item.code"
              @click="handleSelectSpe(item, schoolFeatureDataList)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <!-- 办学类型 -->
        <div class="type-list" :ref="(el) => (sectionRefs[3] = el)">
          <div class="type-title">办学类型</div>
          <div class="type-content">
            <div
              :class="['content-item', item.checked ? 'active' : '']"
              v-for="item in schoolNatureDataList"
              :key="item.code"
              @click="handleSelectItem(item)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <!-- 办学层次 -->
        <div class="type-list" :ref="(el) => (sectionRefs[4] = el)">
          <div class="type-title">办学层次</div>
          <div class="type-content">
            <div
              :class="['content-item', item.checked ? 'active' : '']"
              v-for="item in schoolLevelDataList"
              :key="item.code"
              @click="handleSelectItem(item)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="bottom-btn">
        <div :class="['left-btn', isActive ? 'active' : '']" @click="clear">
          清除已选类型
        </div>
        <div class="right-btn" @click="confirm">确 定</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  nextTick,
  watch,
  computed,
} from 'vue';
import locationProvinceData from '@/utils/locationProvinceData';
import schoolTypeData from '@/utils/schoolTypeData';
import schoolFeatureData from '@/utils/schoolFeatureData';
import schoolNatureData from '@/utils/schoolNatureData';
import schoolLevelData from '@/utils/schoolLevelData';
import { onBeforeRouteLeave } from 'vue-router';

const locationProvinceDataList = ref(locationProvinceData);
const schoolTypeDataList = ref(schoolTypeData);
const schoolFeatureDataList = ref(schoolFeatureData);
const schoolNatureDataList = ref(schoolNatureData);
const schoolLevelDataList = ref(schoolLevelData);
const currentType = ref(1);

const typeList = ref([
  {
    name: '院校地区',
    value: 1,
  },
  {
    name: '院校类型',
    value: 2,
  },
  {
    name: '院校特色',
    value: 3,
  },
  {
    name: '办学类型',
    value: 4,
  },
  {
    name: '办学层次',
    value: 5,
  },
]);

const mainContentRef = ref(null);
const sectionRefs = reactive([]); // 用于收集每个section的DOM

const handleChangeType = (item) => {
  // 立即设置标志，防止滚动事件干扰
  isScrollingByClick = true;
  currentType.value = item.value;
  nextTick(() => {
    const section = sectionRefs[item.value - 1];
    const mainContent = mainContentRef.value;
    if (section && mainContent) {
      // 计算section相对于mainContent的top距离
      const offset = section.offsetTop - mainContent.offsetTop;
      mainContent.scrollTo({ top: offset, behavior: 'smooth' });
    }
  });
};

const handleSelectItem = (item) => {
  item.checked = !item.checked;
  getSelectedData();
};

const handleSelectSpe = (item, list) => {
  item.checked = !item.checked;
  // 点击了不限
  if (!item.code) {
    list.forEach((item) => {
      item.checked = false;
    });
    item.checked = true;
  } else {
    // 点击了其他类型,重置不限
    list[0].checked = false;
  }
  getSelectedData();
};

const clear = () => {
  locationProvinceDataList.value.forEach((item) => {
    item.provinceList.forEach((item) => {
      item.checked = false;
    });
  });
  schoolTypeDataList.value.forEach((item) => {
    item.checked = false;
  });
  schoolFeatureDataList.value.forEach((item) => {
    item.checked = false;
  });
  schoolNatureDataList.value.forEach((item) => {
    item.checked = false;
  });
  schoolLevelDataList.value.forEach((item) => {
    item.checked = false;
  });
  getSelectedData();
};

const selectProvince = ref([]);
const selectSchoolType = ref([]);
const selectSchoolFeature = ref([]);
const selectSchoolNature = ref([]);
const selectSchoolLevel = ref([]);

const getSelectedData = () => {
  selectProvince.value = [];
  locationProvinceDataList.value.forEach((item) => {
    item.provinceList.forEach((item) => {
      if (item.checked) {
        selectProvince.value.push(item);
      }
    });
  });
  selectSchoolType.value = schoolTypeDataList.value.filter((item) => {
    return item.checked && item.name !== '不限';
  });
  selectSchoolFeature.value = schoolFeatureDataList.value.filter((item) => {
    return item.checked && item.name !== '不限';
  });
  selectSchoolNature.value = schoolNatureDataList.value.filter((item) => {
    return item.checked;
  });
  selectSchoolLevel.value = schoolLevelDataList.value.filter((item) => {
    return item.checked;
  });
};

const isActive = computed(() => {
  return (
    selectProvince.value.length > 0 ||
    selectSchoolType.value.length > 0 ||
    selectSchoolFeature.value.length > 0 ||
    selectSchoolNature.value.length > 0 ||
    selectSchoolLevel.value.length > 0
  );
});

const emit = defineEmits(['confirm']);

const confirm = () => {
  const params = {
    selectProvince: selectProvince.value,
    selectSchoolType: selectSchoolType.value,
    selectSchoolFeature: selectSchoolFeature.value,
    selectSchoolNature: selectSchoolNature.value,
    selectSchoolLevel: selectSchoolLevel.value,
  };
  emit('confirm', params);
};

let isScrollingByClick = false;

const handleScroll = () => {
  if (isScrollingByClick) return;
  const scrollTop = mainContentRef.value.scrollTop;
  let activeIndex = 0;
  for (let i = 0; i < sectionRefs.length; i++) {
    const section = sectionRefs[i];
    if (
      section &&
      section.offsetTop - mainContentRef.value.offsetTop <= scrollTop + 10
    ) {
      activeIndex = i;
    }
  }
  currentType.value = activeIndex + 1;
};

onBeforeRouteLeave(() => {
  clear();
});

onMounted(() => {
  if (mainContentRef.value) {
    mainContentRef.value.addEventListener('scroll', handleScroll);
  }
});
onBeforeUnmount(() => {
  if (mainContentRef.value) {
    mainContentRef.value.removeEventListener('scroll', handleScroll);
  }
});

// 防止点击左侧时触发滚动联动
watch(currentType, (val, oldVal) => {
  if (val !== oldVal && isScrollingByClick) {
    // 延长标志的持续时间，确保滚动动画完成
    setTimeout(() => {
      isScrollingByClick = false;
    }, 800);
  }
});
</script>

<style scoped lang="scss">
.college-dialog {
  position: absolute;
  top: 60px;
  left: 0;
  width: 60vw;
  height: 450px;
  z-index: 99;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  box-shadow: 0px 2px 28px 6px rgba(90, 122, 162, 0.3);
  overflow: hidden;
  .left {
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-shrink: 0;
    border-right: 1px solid #e7e7e7;
    .left-item {
      padding: 20px 40px;
      font-size: 24px;
      color: #666666;
      &.active {
        font-weight: bold;
        color: $primary-color;
        background: #f6fafe;
      }
    }
  }
  .right {
    flex: 1;
    height: 100%;
    position: relative;
    .main-content {
      height: calc(100% - 80px);
      overflow-y: auto;
      padding: 0 25px 20px 25px;
      box-sizing: border-box;
      .type-title {
        font-weight: bold;
        font-size: 26px;
        color: #222222;
        padding-top: 20px;
      }
      .content-item {
        font-size: 22px;
        color: #555550;
        background: #f5f8ff;
        border-radius: 4px;
        width: 150px;
        text-align: center;
        box-sizing: border-box;
        border: 2px solid transparent;
        padding: 10px 0;
        &.active {
          background: #e5edff;
          border-radius: 4px;
          border: 2px solid $primary-color;
          font-weight: bold;
          color: $primary-color;
        }
        &.feature {
          width: auto;
          padding: 10px 28px;
        }
      }
      .location-list {
        display: flex;
        flex-direction: column;
        gap: 24px;
        .location-item {
          .location-title {
            font-weight: bold;
            font-size: 24px;
            color: #666;
            margin-bottom: 14px;
          }
          .location-content {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
          }
        }
      }
      .type-list {
        display: flex;
        flex-direction: column;
        gap: 24px;
        margin-top: 20px;
        .type-title {
          font-weight: bold;
          font-size: 24px;
          color: #222;
          padding-top: 12px;
        }
        .type-content {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
        }
      }
    }

    .bottom-btn {
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      padding: 12px;
      background: #ffffff;
      box-shadow: 0px -1px 4px 0px rgba(144, 167, 212, 0.5);
      box-sizing: border-box;
      display: flex;
      flex-direction: row;
      justify-content: center;
      gap: 24px;
      z-index: 2;

      .left-btn,
      .right-btn {
        flex-shrink: 0;
        background: #f8f8f8;
        border-radius: 12px;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: bold;
        font-size: 24px;
        color: #999999;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 296px;
        padding: 10px 0;
      }

      .left-btn {
        background: #f8f8f8;
        border: 1px solid #f8f8f8;
        &.active {
          border: 1px solid $primary-color;
          color: $primary-color;
        }
      }
      .right-btn {
        color: #ffffff;
        background: $primary-color;
      }
    }
  }
}
</style>
